package com.atguigu.gmall.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.dubbo.rpc.RpcContext;
import com.atguigu.gmall.bean.Person;
import com.atguigu.gmall.component.RequestContext;
import com.atguigu.gmall.component.RequestContextStore;
import com.atguigu.gmall.service.PersonService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @author Jerry.Su
 * @Date 2022/2/17 16:27
 */

@Service(filter = "traceId")
@Component
public class PersonServiceImpl implements PersonService {

    private static final Logger log = LoggerFactory.getLogger(PersonServiceImpl.class);

    @HystrixCommand
    @Override
    public List<Person> getPersonListByOrderId(String orderId) {
        String traceId = (String) RpcContext.getContext().get(RequestContextStore.TRACE_ID_KEY);
        traceId = RequestContext.getTraceId();
        log.info("get traceId {} from consumer side", traceId);
//        if (Math.random() > 0.5) {
//            throw new RuntimeException("bad luck");
//        }
        int num = new Random().nextInt(10);
        List<Person> persons = new ArrayList<>();
        for (int i = 0; i < num; i++) {
            persons.add(new Person(new Random().nextInt(30), "jerry" + i, new Random().nextInt(2) > 0 ? "女" : "男"));
        }
        return persons;
    }
}
